#define _CRT_SECURE_NO_WARNINGS



//https://www.luogu.com.cn/problem/P2910


#include<iostream>
using namespace std;
const int N = 110, M = 10010;
int n, m;
int a[M];
int dp[N][N];
int main()
{
	cin >> n >> m;
	for (int i = 1; i <= m; i++)
		cin >> a[i];

	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= n; j++)
			cin >> dp[i][j];

	for (int k = 1; k <= n; k++)
		for (int i = 1; i <= n; i++)
			for (int j = 1; j <= n; j++)
				dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j]);

	long long ret = 0;
	for (int i = 2; i <= m; i++)
	{
		int x = a[i - 1];
		int y = a[i];
		ret += dp[x][y];
	}
	cout << ret;
	return 0;
}






